package com.hexb.core.aop;

import com.hexb.core.enums.AscColors;
import com.hexb.core.jdbc.DynamicDataSourceContextHolder;
import com.hexb.core.jdbc.TargetDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Package : com.hexb.core.service
 * @Author : hexb
 * @Date : 2018-08-7 11:18
 */
@Aspect
@Component
@Order(-1)
@ConditionalOnProperty(value = "project.multipleDataSource", havingValue = "true")
@Slf4j
public class DynamicDataSourceAspect {


    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        String dataSourceName = targetDataSource.value();
        if (!StringUtils.isEmpty(dataSourceName)) {
            log.info(String.format("%s====>%s Use Data Source %s%s", AscColors.YELLOW, AscColors.VIOLET, dataSourceName, AscColors.END));
            DynamicDataSourceContextHolder.setDataSourceName(dataSourceName);
        }
    }


    @After("@annotation(targetDataSource)")
    public void resetDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        DynamicDataSourceContextHolder.clearDataSourceName();
    }

}
